import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from "@nestjs/common";
import { ResultData } from 'src/common/utils/result';
import { CreateInfoDto, QueryInfoDto, UpdateInfoDto } from './dto/info.dto';
import { InfoEntity } from './entities/info.entity';
import { isEmpty } from 'src/common/utils';
import { UserService } from '../user/user.service';
import { SettingsService } from '../settings/settings.service';
import { SmsService } from '../sms/sms.service';

@Injectable()
export class InfoService {
  constructor(
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @InjectRepository(InfoEntity)
    private readonly infoEntityRep: Repository<InfoEntity>,
    private readonly settingsService: SettingsService,
    private readonly smsService: SmsService,
  ) {}

  private logger = new Logger(InfoService.name);

  async create(createInfoDto: CreateInfoDto) {

    // 检查用户名是否已存在
    const checkUserNameUnique = await this.userService.checkUserNameUnique(createInfoDto.loginAccount);

    if (checkUserNameUnique) {
      return ResultData.fail(500, `保存用户'${checkUserNameUnique.userName}'失败，注册账号已存在`);
    }

    // 注册用户
    const user = await this.userService.createClient({
      deptId: 102,
      userName: createInfoDto.loginAccount,
      nickName: createInfoDto.childNickname,
      password: createInfoDto.loginPassword,
      phonenumber: '',
      sex: createInfoDto.childGender,
      avatar: createInfoDto.avatar,
      email: '',
    });
    createInfoDto.userId = user.userId;
    // 添加孩子信息
    const res = await this.infoEntityRep.save(createInfoDto);

    // 添加孩子防沉迷设置信息
    await this.settingsService.create({
      childId: res.userId,
      type: 1,
      repeatDays: '1,2,3,4,5,6,0',
      isDaily: 1,
      startHour: 0,
      startMinute: 0,
      endHour: 23,
      endMinute: 59,
    });

    return ResultData.ok(res);
  }

  async findAll(query: QueryInfoDto) {
    const entity = this.infoEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.userId)) {
      entity.andWhere('entity.userId = :userId', { userId: query.userId });
    }
    if (!isEmpty(query.loginAccount)) {
      entity.andWhere('entity.loginAccount = :loginAccount', { loginAccount: query.loginAccount });
    }
    if (!isEmpty(query.loginPassword)) {
      entity.andWhere('entity.loginPassword = :loginPassword', { loginPassword: query.loginPassword });
    }
    if (!isEmpty(query.childNickname)) {
      entity.andWhere('entity.childNickname LIKE :childNickname', { childNickname: `%${query.childNickname}%` });
    }
    if (!isEmpty(query.childGender)) {
      entity.andWhere('entity.childGender = :childGender', { childGender: query.childGender });
    }
    if (!isEmpty(query.personality)) {
      entity.andWhere('entity.personality = :personality', { personality: query.personality });
    }
    if (!isEmpty(query.hobbies)) {
      entity.andWhere('entity.hobbies = :hobbies', { hobbies: query.hobbies });
    }
    if (!isEmpty(query.communicationAppeal)) {
      entity.andWhere('entity.communicationAppeal = :communicationAppeal', { communicationAppeal: query.communicationAppeal });
    }
    if (!isEmpty(query.status)) {
      entity.andWhere('entity.status = :status', { status: query.status });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', {
        start: query.createTime[0],
        end: query.createTime[1],
      });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', {
        start: query.updateTime[0],
        end: query.updateTime[1],
      });
    }
    entity.select([
      'entity.userId',
      'entity.loginAccount',
      'entity.loginPassword',
      'entity.childNickname',
      'entity.childGender',
      'entity.personality',
      'entity.hobbies',
      'entity.communicationAppeal',
      'entity.status',
    ]);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findAllList() {
    const entity = this.infoEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0', status: '1' });

    entity.select([
      'entity.userId',
      'entity.loginAccount',
      'entity.loginPassword',
      'entity.childNickname',
      'entity.childGender',
      'entity.personality',
      'entity.hobbies',
      'entity.communicationAppeal',
      'entity.status',
    ]);

    const [list, total] = await entity.getManyAndCount();

    return list;
  }

  async myChildList(userId: number) {
    const sql = `
        select ci.user_id as        childId,
               ci.avatar as         avatar,
               ci.child_nickname as childNickname,
               ci.status as         status,
               ci.end_time as       endTime,
               aas.type as          type,
               aas.is_daily as      isDaily,
               aas.start_hour as    startHour,
               aas.start_minute as  startMinute,
               aas.end_hour as      endHour,
               aas.end_minute as    endMinute
        from child_info ci
                 left join anti_addiction_settings aas on ci.user_id = aas.child_id and aas.del_flag = '0'
        where ci.del_flag = '0'
          and ci.parent_id = ?
        order by ci.create_time;
    `;

    // 执行原生SQL查询
    return ResultData.ok(await this.infoEntityRep.query(sql, [userId]));
  }

  async findOne(userId: number) {
    const res = await this.infoEntityRep.findOne({
      where: {
        delFlag: '0',
        userId: userId,
      },
    });
    return ResultData.ok(res);
  }

  // async findOne(userId: number) {
  //
  //   return await this.infoEntityRep.findOne({
  //     where: {
  //       delFlag: '0',
  //       c: userId,
  //     },
  //   });
  // }

  /**
   * 更新孩子信息及关联的用户信息
   * @param updateInfoDto 包含更新信息的数据传输对象
   * @returns 更新结果
   */
  async update(updateInfoDto: UpdateInfoDto) {
    // 检查用户名唯一性，确保用户名不与其他用户冲突
    await this.userService.checkUserNameUserIdUnique(updateInfoDto.loginAccount, updateInfoDto.userId);

    // 更新关联的用户信息
    await this.userService.updateClient({
      userId: updateInfoDto.userId,
      userName: updateInfoDto.loginAccount,
      nickName: updateInfoDto.childNickname,
      sex: updateInfoDto.childGender,
      avatar: updateInfoDto.avatar,
      password: updateInfoDto.loginPassword,
    });

    // 更新孩子信息
    const res = await this.infoEntityRep.update({ userId: updateInfoDto.userId }, updateInfoDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  /**
   * 更新会员状态
   * @returns 更新结果
   * @param userId 用户id
   * @param endTime 会员结束时间
   */
  async updateMemberStatus(userId: number, endTime: Date) {
    // 更新孩子信息
    const res = await this.infoEntityRep.update({ userId }, { endTime, status: '1' });
    return res.affected >= 1;
  }

  async remove(userId: number) {
    await this.userService.removeChildren(userId);
    const res = await this.infoEntityRep.update(
      { userId: userId },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }

  /**
   * 检查会员是否过期
   */
  async checkAndUpdateExpiredMembers() {
    this.logger.log('开始检查会员状态');
    const currentDate = new Date();

    // 查询所有未删除且状态为正常的会员记录
    const expiredMembers = await this.infoEntityRep
      .createQueryBuilder('entity')
      .where('entity.delFlag = :delFlag', { delFlag: '0' })
      .andWhere('entity.status = :status', { status: '1' })
      .andWhere('entity.endTime < :currentDate', { currentDate })
      .getMany();

    // 批量更新过期会员的状态
    if (expiredMembers.length > 0) {
      const userIds = expiredMembers.map((member) => member.userId);
      await this.infoEntityRep.createQueryBuilder().update(InfoEntity).set({ status: '0' }).where('user_id IN (:...userIds)', { userIds }).execute();
    }

    this.logger.log(`已更新过期会员状态: ${expiredMembers.length}`);
  }

  /**
   * 查询即将过期的会员（距离当前时间少于3天）
   */
  async findExpiringMembers() {
    this.logger.log('开始查询即将过期的会员');

    // 使用原生SQL查询即将过期会员的家长手机号
    const sql = `
        SELECT DISTINCT u.phonenumber
        FROM sys_user u
        WHERE u.user_id IN (
            SELECT c.parent_id
            FROM child_info c
            WHERE c.del_flag = '0'
              AND c.status = '1'
              AND c.end_time BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 3 DAY)
        )
          AND u.del_flag = '0'
          AND u.status = '0';
    `;

    // 执行原生SQL查询
    const phoneNumbers = await this.infoEntityRep.query(sql);

    // 循环发送短信
    if (phoneNumbers.length > 0) {
      for (const item of phoneNumbers) {
        if (item.phonenumber) {
          // 发送预警短信提醒
          await this.smsService.sendSms(String(item.phonenumber), '上海智影慧心数字科技', 'SMS_495950131', '');
        }
      }
    }

    this.logger.log(`查询到即将过期的会员家长数量: ${phoneNumbers.length}`);
  }

  async getOpenid(parentId: number) {
    // 查询家长的openid
    const openId = await this.userService.getOpenid(parentId);
    return openId || '';
  }
}
